Java final keyword

The final keyword in java is used to declare any variable or method or class as constants.

So, any variable that is declared as final will not be able to be reinitialized with another value.

If any method is declared with final, cannot be overridden.

Classes that are declared as final, cannot be extended.

Example for final variable

class Main {
  public static void main(String[] args) {

    // create a final variable
    final int EXPERIENCE = 5;

    // trying to change the final variable
    EXPERIENCE = 7;
    System.out.println("Experience: "+EXPERIENCE);
  }
}

In the above program, we have a final variable EXPERIENCE whose initial value is 5. Later we try to re-assign new value to EXPERIENCE variable.

Running the above program, will throw an error as below

Main.java:8: error: cannot assign a value to final variable ExPERIENCE
    ExPERIENCE = 7;

Example for final method

class Employee {
    // create a final method
    public final void display() {
      System.out.println("Welcome to Readersbuddy");
    }
}

class Main extends Employee {
  // try to override final method
  public final void display() {
    System.out.println("Welcome to Java");
  }

  public static void main(String[] args) {
    Main myObj = new Main();
    myObj.display();
  }
}

In the above program, we have created a class Employee with a function display() as final.

Next, we extend the Employee class in the Main class and try to override the display() function.

Running the above program will throw an error as below.

Main.java:10: error: display() in Main cannot override display() in Employee
  public final void display() {
                    ^
  overridden method is final

This is because, final method cannot be overridden.

Example for final class

final class Employee {
    public void display() {
      System.out.println("Welcome to Readersbuddy");
    }
}

class Main extends Employee {

  public static void main(String[] args) {
    Main myObj = new Main();
    myObj.display();
  }
}

This is because we have declared the Employee class as final and then we try to inherit the Employee class by Main class.

Running the above program will result in throwing an error,

Main.java:7: error: cannot inherit from final Employee
class Main extends Employee {

Most Read